<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" title="盘点计划" displayable="true" color="#000000" backgroundColor="#FFFFFF" />
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入盘点计划单号" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" @leftIconClick="scanCode" radius="30" :showFilter="true">
        <template v-slot:searchFields>
          <view class="search-fields">
            <eui-card-input v-model="formData.c_status" title="单据状态" placeholder="请选择单据状态"
                            :range="statusList" type="multi" alignType="left" />
            <eui-card-input v-model="formData.c_count_dt_s" title="开始日期" rightIconType="right"
                            placeholder="请选择录入开始日期" type="date" :displayable="displayable" />
            <eui-card-input v-model="formData.c_count_dt_e" title="结束日期" rightIconType="right"
                            placeholder="请选择录入结束日期" type="date" :displayable="displayable" />
            <view class="bottom flex-1 flex">
              <eui-button type="max2" title="重置" singleTag="reset" @buttonClick="confirm"></eui-button>
              <eui-button type="max" title="确认" singleTag="fix" @buttonClick="confirm"></eui-button>
            </view>
          </view>
        </template>
      </eui-search-bar>
    </view>
    <view class="main-view" :style="{ height: listHeight + 'rpx' }">
      <eui-virtual-list @onRefresh="getData" @lower="templateLower" refresher="true"
                        :origList="dataList" :isBottom="true" type="list">
        <template v-slot:list="scope">
          <eui-text title="盘点类型" :value="sysConfig.c_count_type[scope.c_count_type]" type="number2" />
          <eui-text title="盘点时效性" :value="sysConfig.c_count_time[scope.c_count_time]" type="number2" />
          <eui-text title="清零方式" :value="sysConfig.c_clear_mode[scope.c_clear_mode]" type="number2" />
          <eui-text title="是否指定仓库" :value="sysConfig.c_is_select[scope.c_is_wno]" type="number2" />
          <eui-text title="是否指定部门" :value="sysConfig.c_is_select[scope.c_is_adno]" type="number2" />
          <eui-text title="是否指定品类" :value="sysConfig.c_is_select[scope.c_is_gdsclass]" type="number2" />
          <eui-text title="是否指定品牌" :value="sysConfig.c_is_select[scope.c_is_brand]" type="number2" />
          <eui-text title="是否指定商品" :value="sysConfig.c_is_select[scope.c_is_gcode]" type="number2" />
        </template>
        <template v-slot:bottom="scope">
          <view>
            <eui-button :modelValue="scope" type="min" single-tag="confirm" title="生成盘点单"
                        @buttonClick="buttonClick" v-if="scope.c_status == '3'"/>
          </view>
        </template>
      </eui-virtual-list>
    </view>
  </view>
</template>

<script setup type="ts">
import dayjs from 'dayjs';
import { ref, reactive, onMounted } from 'vue';
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import { validateStores } from '@/hooks/useValidateMethod';
import {getRdsUrl, rdsRequest} from '@/hooks/rdsServices';
import { getRelatedName, getDictName, getDictSelectList, getDictList } from '../components/RelatedName.js';
import service from "@/common/service";
import dateRangUtil from '../../../common/dateRangUtil';
import {onLoad} from "@dcloudio/uni-app";
import { init, getRdsUserDepartAuthority } from '@/hooks/init';
import useBillType from "@/hooks/useBillType";
import Enjoy from "@/common/enjoy";
import { auditCount } from './app.js'
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const storeId = ref('');
const searchText = ref('');
const CurrentPage = ref(1);  //第几页
const PageSize = ref(10);  //每页10条
const RowsCount = ref(0);  //总条数
const PageCount = ref(1);  //总页数
const displayable = ref(false);
const dataList = ref([]);
const c_status = ref('0');
const showRightStyle = ref('text-align: right');
const formData = ref({
  c_count_dt_s: (dateRangUtil.getLast1Month())[0],
  c_count_dt_e: (dateRangUtil.getLast1Month())[2],
  c_status: '3', // 默认排查 已作废 和 已终止
}) //查询表单
const sysConfig = ref({
  c_status: {}, // 单据状态
  c_count_type: {}, // 盘点类型
  c_count_time: {}, // 盘点时效性
  c_clear_mode: {}, // 盘点清零方式
  c_is_select: {}, // 是否指定
});
const statusList = ref([]); // 查询条件状态下拉框
const listHeight = ref(300);  // 列表高度
const RdsSearchBar = ref(null);
const EuiNavBar = ref(null);

// 选择框点击事件
const clickStore = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  parms.SelectionType = "机构选择";
  parms.SelectedItems = sUserStore.value;
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (event) => {
  if (event.SelectionType == '机构选择') {
    // 更新机构信息
    sUserStoreName.value = event.BackParms.Value;
    sUserStore.value = event.BackParms.Key;
  }
  // 按新条件获取数据
  await getData();
}

onLoad(async ({storeId}) => {
  await init();
  await getSysConfig();
  await setDefault(storeId);
  getData();
})

// 获取系统参数、字典
const getSysConfig = async () => {
  (await getDictList("单据状态")).forEach(e => {
    sysConfig.value.c_status[e.c_id] = e.c_name;
    statusList.value.push({
      text: e.c_name,
      value: e.c_id,
      checked: formData.value.c_status.includes(e.c_id)
    });
  });
  (await getDictList("盘点类型")).forEach(item => sysConfig.value.c_count_type[item.c_id] = item.c_name);
  (await getDictList("盘点时效性")).forEach(item => sysConfig.value.c_count_time[item.c_id] = item.c_name);
  (await getDictList("盘点清零方式")).forEach(item => sysConfig.value.c_clear_mode[item.c_id] = item.c_name);
  (await getDictList("盘点模型是否")).forEach(item => sysConfig.value.c_is_select[item.c_id] = item.c_name);
}

const setDefault = async (store_id) => {
  const { loginInfo } = mainStore;
  sUserStore.value = loginInfo.sUserStore;
  sUserStoreName.value = loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
  storeId.value = store_id
  formData.value.c_count_userno = loginInfo.sUser;
}

// 点击扫描图标跳转打开摄像头
const scanCode = () => {
  uni.scanCode({
    success: function (res) {
      if (res.result != '' && res.result != undefined && res.result != null) {
        searchText.value = res.result;
        getData();
      }
    },
  });
}

const searchConfirm = async (e) => {
  if (!e) {
    return;
  }
  searchText.value = e.value;
  await getData();
}

const getData = async (e) => {
  if (!e) {
    CurrentPage.value = 1;
  }
  const objectData = {
    IsNotPage: false,
    CurrentPage: CurrentPage.value,
    PageSize: PageSize.value,
    UserNo: sUser.value,
    WhereList: searchText.value == '' ? [
      {
        c_col: 'c_count_dt',
        c_oper: '大于等于',
        c_value: formData.value.c_count_dt_s,
        c_col_dtype: 'System.DateTime',
        c_logic: '而且',
      },
      {
        c_col: 'c_count_dt',
        c_oper: '小于等于',
        c_value: formData.value.c_count_dt_e,
        c_col_dtype: 'System.DateTime',
        c_logic: '而且',
      },
      {
        c_col: 'c_status',
        c_oper: '包含',
        c_value: formData.value.c_status,
        c_logic: '而且',
      },
    ] : [
      {
        c_col: 'c_id',
        c_oper: '等于',
        c_value: searchText.value,
        c_logic: '而且',
      }
    ],
  };
  service.enjoyShowLoading('正在加载...');
  const result = await rdsRequest(rdsUrl.scApi, '盘点计划单', 'EnjoyQueryList', objectData);
  CurrentPage.value = result.CurrentPage; //第几页
  PageSize.value = result.PageSize; //每页10条
  RowsCount.value = result.RowsCount; //总条数
  PageCount.value = result.PageCount; //总页数
  if (result.CurrentPage == 1) {
    dataList.value = result.ReturnObject;
  } else {
    dataList.value = dataList.value.concat(result.ReturnObject);
  }
  dataList.value.forEach(x => {
    x.c_date = dayjs(x.c_count_dt).format('MM/DD');
  })
  service.enjoyHideLoading();
}

// 上拉加载更多
const templateLower = () => {
  if (CurrentPage.value < PageCount.value) {
    CurrentPage.value = CurrentPage.value + 1;
    getData(true);
  }
}

const confirm = (t) => {
  let { singleTag } = t;
  switch (singleTag) {
    case 'reset':
      formData.value.c_count_dt_s = (dateRangUtil.getLast1Month())[0];
      formData.value.c_count_dt_e = (dateRangUtil.getLast1Month())[2];
      formData.value.c_status = '3';
      statusList.value.forEach(item => item.value == '3' ? item.checked = true : item.checked= false)
      break;
    case 'fix':
      getData();
      // 关闭弹出层
      RdsSearchBar.value.closeDrawer();
      break;
  }
}

const buttonClick = (e) => {
  let { singleTag, modelValue, type } = e;
  switch (singleTag) {
    case 'confirm':
      createCountMain(modelValue);
      break;
  }
}

// 生成盘点单
const createCountMain = async (e) => {
  console.log('生成盘点单=========e: ', e);
  service.enjoyShowLoading('正在加载...');
  const adno = await getRdsUserDepartAuthority();
  console.log('=====adno: ', adno);
  const objectData = {
    bill_id: e.c_id,
    store_id: [storeId.value],
    wno: ['00'],
    adno: adno,
    gmode: '',
    is_recover: '0',
    login_store_id:'',
  };
  const { billTypes } = await useBillType();
  console.log('=========billTypes: ', billTypes);
  const {  c_bill_type } = billTypes.find(item => item.c_name === '盘点计划单'); //B01
  const res = await rdsRequest(rdsUrl.scApi, '商品盘点单', 'CreateCountMain', objectData, c_bill_type);
  console.log('=====res: ', res);
  service.enjoyHideLoading();
  uni.showToast({
    duration: 3500,
    icon: 'none',
    title: `${res.msg}${res.billId ? ' 生成盘点单: ' + res.billId : ' 没有生成盘点单'} !`,
    mask: true,
  });
}


</script>

<style lang="scss" scoped>
@import '../../../main.scss';
.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}
.top-view {
  width: 100%;
  height: 88rpx;
  background: #FFFFFF;
  margin-bottom: 20rpx;
}
.main-view {
  flex: 1;
  flex-direction: column;
}
.search-fields {
  width: 100%;
  background: #FFFFFF;
  position: relative;

  .bottom {
    background: #ffffff;
    border-top: 1rpx solid $uni-line-color;
    display: flex;
    justify-content: center;
    padding: 20rpx;
  }
}
</style>
